package com.dollkey.hdownload.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.AttributeSet;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.dollkey.hdownload.util.ValidateUtil;


public class ProgressWebView extends WebView {
    private WebChromeClient mWebChromeClient;
//    private ProgressBar mProgressBar;

    public ProgressWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
//        mProgressBar = new ProgressBar(context, null,
//                android.R.attr.progressBarStyleHorizontal);
//        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT, DisplayUtils.dp2px(context, 3));
//        mProgressBar.setLayoutParams(layoutParams);

//        Drawable drawable = context.getResources().getDrawable(
//                R.drawable.web_progress_bar_status);
//        mProgressBar.setProgressDrawable(drawable);
//        addView(mProgressBar);
        mWebChromeClient = new WebChromeClient();
        setWebChromeClient(mWebChromeClient);
        // 创建WebViewClient对象
        WebViewClient wvc = new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 使用自己的WebView组件来响应Url加载事件，而不是使用默认浏览器器加载页面
                //                view.loadUrl(url);

                // 消耗掉这个事件。Android中返回True的即到此为止吧,事件就会不会冒泡传递了，我们称之为消耗掉
                if (ValidateUtil.isUrl(url)) {
                    return super.shouldOverrideUrlLoading(view, url);//（步骤三）
                } else {
                    return true;
                }
            }

            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                // 这个方法在6.0才出现
                //                int statusCode = errorResponse.getStatusCode();
                if (request.getUrl().toString().equals(getUrl())) {
                    if (mOnReceivedTitleListener != null)
                        mOnReceivedTitleListener.onReceivedError();
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                // 断网或者网络连接超时
                if (errorCode == ERROR_HOST_LOOKUP || errorCode == ERROR_CONNECT || errorCode == ERROR_TIMEOUT) {
                    if (mOnReceivedTitleListener != null)
                        mOnReceivedTitleListener.onReceivedError();
                }
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if (mOnReceivedTitleListener != null)
                    mOnReceivedTitleListener.onPageState(true);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (mOnReceivedTitleListener != null)
                    mOnReceivedTitleListener.onPageState(false);
            }
        };
        setWebViewClient(wvc);
        //是否可以缩放
        requestFocusFromTouch();
        WebSettings webSettings = getSettings();
        webSettings.setBuiltInZoomControls(false);
        // 设置与Js交互的权限
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        //支持插件
        webSettings.setPluginState(WebSettings.PluginState.ON);
        // 设置允许JS弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        //设置适应屏幕
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //支持缩放
        webSettings.setSupportZoom(false);
        //隐藏原生的缩放控件
        webSettings.setDisplayZoomControls(false);

        //支持内容重新布局
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.supportMultipleWindows();
        webSettings.setSupportMultipleWindows(true);

        //设置缓存模式
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);

        ConnectivityManager connectivityManager = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo.isAvailable()) {
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//网络正常时使用默认缓存策略
        } else {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);//网络不可用时只使用缓存
        }
//        getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAppCacheEnabled(true);
        webSettings.setAppCachePath(getContext().getCacheDir().getAbsolutePath());

        //设置可访问文件
        webSettings.setAllowFileAccess(true);
        //当webview调用requestFocus时为webview设置节点
        webSettings.setNeedInitialFocus(true);

        //支持自动加载图片
        if (Build.VERSION.SDK_INT >= 19) {
            webSettings.setLoadsImagesAutomatically(true);
        } else {
            webSettings.setLoadsImagesAutomatically(false);
        }

        //设置编码格式
        webSettings.setDefaultTextEncodingName("UTF-8");
    }

    public WebChromeClient getWebChromeClient() {
        return mWebChromeClient;
    }

    public class WebChromeClient extends android.webkit.WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
//                mProgressBar.setVisibility(GONE);
//                mProgressBar.setProgress(0);
                if (mOnReceivedTitleListener != null) {
                    mOnReceivedTitleListener.onPageLoadComplete();
                }
            } else {
//                if (mProgressBar.getVisibility() == GONE)
//                    mProgressBar.setVisibility(VISIBLE);
//                mProgressBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (mOnReceivedTitleListener != null)
                mOnReceivedTitleListener.onReceivedTitle(title);

            // android 6.0 以下通过title获取
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                if (title.contains("404") || title.contains("500") || title.contains("Error")) {
                    if (mOnReceivedTitleListener != null)
                        mOnReceivedTitleListener.onReceivedError();
                }
            }
        }
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
//        LayoutParams lp = (LayoutParams) mProgressBar.getLayoutParams();
//        lp.x = l;
//        lp.y = t;
//        mProgressBar.setLayoutParams(lp);
        super.onScrollChanged(l, t, oldl, oldt);
    }

    private OnReceivedTitleListener mOnReceivedTitleListener;

    public void setOnReceivedTitleListener(OnReceivedTitleListener onReceivedTitleListener) {
        mOnReceivedTitleListener = onReceivedTitleListener;
    }

    public interface OnReceivedTitleListener {

        void onReceivedTitle(String title);

        void onReceivedError();

        void onPageState(boolean isStart);

        void onPageLoadComplete();
    }
}